#include "cvolumemanager.h"
#include <buola/dbus/cproxy.h>
#include <buola/system/cdiskmanager.h>
#include <buola/gui/cmenu.h>

namespace buola { namespace bdesktop {

CVolumeManager::CVolumeManager(CDock *pDock)
    :   mDock(pDock)
{
    system::CDiskManager &lManager=system::get_disk_manager();
    
    std::vector<system::PDiskDevice> lVolumes;
    lManager.GetVolumes(lVolumes);
    lManager.sDeviceAdded.Connect(&CVolumeManager::OnDeviceAdded,this,_1);
    lManager.sDeviceRemoved.Connect(&CVolumeManager::OnDeviceRemoved,this,_1);
    
    for(int i=0;i<lVolumes.size();i++)
    {
        mVolumes[lVolumes[i]->GetID()]=new CVolume(this,lVolumes[i]);
    }
    
    MountAll();
}

CVolumeManager::~CVolumeManager()
{
}

void CVolumeManager::MountAll()
{
    return;
    for(auto i=mVolumes.begin();i!=mVolumes.end();++i)
    {
        CVolume *lV=i->second;
        if(!lV->ShouldAutomount()) continue;
        lV->Mount();
    }
}

void CVolumeManager::LaunchBrowser(const CURL &pURL)
{
    dbus::CProxy lProxy(dbus::get_session_bus(),"org.buola.Browser","/org/buola/Browser");
    lProxy.CallIgnore("org.buola.Browser","NewWindow",pURL);
}

void CVolumeManager::FillPlacesMenu(gui::PMenu pMenu)
{
    pMenu->Add(gui::new_menu_item(L"Home folder","user-home",nullptr,CURL::GetHome().GetWURL()))->
                    eTriggered.Connect(&CVolumeManager::LaunchBrowser,this,CURL::GetHome());
    pMenu->Add(gui::new_menu_item(L"Desktop","user-desktop",nullptr,(CURL::GetHome()+"Desktop").GetWURL()))->
                    eTriggered.Connect(&CVolumeManager::LaunchBrowser,this,CURL::GetHome()+"Desktop");

    pMenu->AddSeparator();

    for(auto i=mVolumes.begin();i!=mVolumes.end();++i)
    {
        CVolume *lV=i->second;
        if(!lV->ShouldBeInPlacesMenu()) continue;
        lV->AddToPlacesMenu(pMenu);
    }
}

void CVolumeManager::OnDeviceAdded(system::PDiskDevice pDev)
{
    if(!pDev->IsVolume()) return;

    std::string lID=pDev->GetID();
    
    if(!mVolumes[lID])
    {
        CVolume *lV=new CVolume(this,pDev);
        mVolumes[lID]=lV;
        
        if(lV->ShouldAutomount())
        {
            lV->Mount();
        }
    }
}

void CVolumeManager::OnDeviceRemoved(system::PDiskDevice pDev)
{
    if(!pDev->IsVolume()) return;

    std::string lID=pDev->GetID();
    
    if(CVolume *lV=mVolumes[lID])
    {
        mVolumes[lID]=nullptr;
        delete lV;
    }
}

/*namespace bdesktop*/ } /*namespace buola*/ }
